package com.jack.module.jetpack.datastore.preferences

import android.content.Context
import androidx.datastore.DataStore
import androidx.datastore.preferences.Preferences
import androidx.datastore.preferences.createDataStore
import androidx.datastore.preferences.edit
import androidx.datastore.preferences.preferencesKey
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map

/**
 * @author: dingfeng
 * @date: 2020-10-29
 * @since: 1.0.0
 **/
object DataStorePreferences {

    const val preferences_name = "preferences"

    private lateinit var mDataStore: DataStore<Preferences>

    fun init(context: Context) {
        mDataStore = context.createDataStore(
                preferences_name
        )
    }

    suspend fun write(key: String, value: String) {
        val dataStoreKey = preferencesKey<String>(name = key)
        mDataStore.edit { preferences ->
            preferences[dataStoreKey] = value
        }
    }

    suspend fun readData(key: String): String {
        val dataStoreKey = preferencesKey<String>(name = key)
        val dataFlow: Flow<String> = mDataStore.data
                .map { preferences ->
                    preferences[dataStoreKey] ?: ""
                }
        return dataFlow.first()
    }

}